﻿using System;
using System.Windows.Forms;
using CalcSharp.Core;
using CalcSharp.Core.Containers;

namespace CalcSharp.MDIUI
{
    public partial class funct_edit : Form
    {
        public funct_edit()
        {
            InitializeComponent();
        }

        public funct_edit(string fname)
        {
            InitializeComponent();
            if (!string.IsNullOrEmpty(fname))
            {
                this.tb_name.Text = fname;
                if (Program.functionmem.isset(fname)) this.tb_code.Text = Program.functionmem[fname].code;
            }
        }

        private void btn_cancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btn_save_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(this.tb_code.Text)) throw new CSException("Can't save empty code!");
                if (string.IsNullOrEmpty(this.tb_name.Text)) throw new CSException("Function must have a name");
                if (Program.functionmem.isset(this.tb_name.Text))
                {
                    Program.functionmem[this.tb_name.Text.ToUpper()].code = this.tb_code.Text;
                    Program.functionmem[this.tb_name.Text.ToUpper()].reqparams = Convert.ToInt32(this.paramcounter.Value);
                }
                else Program.functionmem[this.tb_name.Text] = new UserFunction(this.tb_code.Text.ToUpper(), Convert.ToInt32(this.paramcounter.Value));
                MessageBox.Show("Function saved as: " + this.tb_name.Text);
                this.Close();
            }
            catch (CSException ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}
